import { memo, useEffect, useState } from 'react'
import { Station } from '../services'
import { useRequest } from 'ahooks'
import { Checkbox, message, Modal, Table } from 'antd'
import { Evcs, QueryEvcsListParams, queryList2, saveEvcs } from '../../evcsList/services'
import { PAGINATION_CONFIG } from '@/constants'
import { ColumnsType } from 'antd/es/table'

export interface EvcsModalProps {
  record?: Station
  onCancel?: () => void
}

const EvcsModal: React.FC<EvcsModalProps> = props => {
  const [searchParams, setSearchParams] = useState<QueryEvcsListParams>({
    pageNum: 1, pageSize: 100,
  })
  const list = useRequest(() => queryList2(searchParams), {
    ready: !!searchParams.stationId,
    refreshDeps: [searchParams],
  })
  const saveEvcsReq = useRequest(saveEvcs, {manual: true})

  const onOk = () => {
    const ids: string[] = []
    list.data?.data.forEach(((val: any) => {
      if (val.status === 1) {
        ids.push(val.id)
      }
    }))
    saveEvcsReq.runAsync({
      stationId: props.record!.id,
      evcsOrgIds: ids.join(',')
    })
    .then(() => {
      message.success('配置成功')
    })
  }
  const onCancel = () => {
    props.onCancel?.()
  }
  const columns: ColumnsType<any> = [
    {
      title: '平台名称',
      dataIndex: 'name',
    },
    {
      title: '开放状态',
      dataIndex: 'status',
      render: (val, record, index) => {
        return <Checkbox checked={val === 1} onChange={() => list.mutate({
          ...list.data!,
          data: list.data!.data.map((item, idx) => ({...item, status: idx === index ? (val === 1 ? 2 : 1) : item.status}))
        })}></Checkbox>
      }
    },
  ]

  useEffect(() => {
    if (props.record) {
      setSearchParams({
        pageNum: 1, 
        pageSize: 100,
        stationId: props.record.id,
      })
    }
  }, [props.record])

  return (
    <Modal
      title='互联互通配置'
      open={!!props.record}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
      okText='保存'
      cancelText='关闭'
      confirmLoading={saveEvcsReq.loading}
    >
      <Table<Evcs>
        rowKey='id'
        loading={list.loading}
        dataSource={list.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: list.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
    </Modal>
  )
}

export default memo(EvcsModal)
